/**
 * 
 */
package kernel_gui.gui.extended;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import kernel_gui.gui.generic.graphic.ControlMovies;

import common.entities.enums.ACTION;
import common.entities.persistent.Actor;
import common.entities.persistent.Country;
import common.entities.persistent.Director;
import common.entities.persistent.Genre;
import common.entities.persistent.Movie;

/**
 * @author Yoyo
 *
 */
public class EControlMovies extends ControlMovies {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2407150267404795893L;
	
	private String titleSubStr = null;
	private int releaseYearMin = -1;
	private int releaseYearMax = -1;
	private float rankMin = -1.0F;
	private float rankMax = -1.0F;
	private Actor actor = null;
	private Actor selected_actor = null;
	private Director director = null;
	private Director selected_director = null;
	private List<Genre> genres = null;
	private Country country = null;
	private Country selected_country = null;
	
	private int count = 0;
	private int numberOfRecordsPerPage;
	private int currentPage = 0;
	private int totalPages = 0;
	
	private List<Movie> currentDataInTableModel;
	private DefaultTableModel currentTableModel = new DefaultTableModel();
	private DefaultListModel<String> currentGenresListModel;
	private List<Genre> currentDataGenresListModel;
	private int numOfGenres;
	
	private int currentRowBeingUpdated = -1;
	private int currentNewRow = -1;
	
	/*General*/
	public EControlMovies() {
		
		/*Command to execute on cancel*/
		setExecuteOnCancel(new CommandToExecute() {
			
			@Override
			public void command(Object answer) {
				Component components[] = MainPanel.getComponents();
				for (Component c : components) {
					if(c instanceof JPanel){
						JPanel panel = (JPanel) c;
						Component pcomponents[] = panel.getComponents();
						for(Component pc : pcomponents){
							if(pc instanceof JPanel){
								JPanel anotherPanel = (JPanel) pc;
								Component pccomponents[] = anotherPanel.getComponents();
								for(Component pcc : pccomponents){
									pcc.setEnabled(true);
								}
							}
							pc.setEnabled(true);
						}
					}
					
					c.setEnabled(true);
				}
				ResultTable.setEnabled(true);
				updateButtonsAndLabelsAfterReturnedResultSet();
				setWindowComponentsWhenCalledFromAnotherFrame();
			}
		});
		
		/*Command to execute before long request*/
		setExecuteBeforeLongRequest(new CommandToExecute() {
			
			@Override
			public void command(Object answer) {
				Component components[] = MainPanel.getComponents();
				for (Component c : components) {
					if(c instanceof JPanel){
						JPanel panel = (JPanel) c;
						Component pcomponents[] = panel.getComponents();
						for(Component pc : pcomponents){
							if(pc instanceof JPanel){
								JPanel anotherPanel = (JPanel) pc;
								Component pccomponents[] = anotherPanel.getComponents();
								for(Component pcc : pccomponents){
									pcc.setEnabled(false);
								}
							}
							pc.setEnabled(false);
						}
					}
					
					c.setEnabled(false);
				}
				ResultTable.setEnabled(false);
			}
		});
		
		/*Update the numberOfRecords variable*/
		NumOfRecordsInPageComboBox.setSelectedIndex(2);
		numberOfRecordsPerPage = Integer.parseInt(NumOfRecordsInPageComboBox.getSelectedItem().toString());
		
		/*Create defaultive model*/
		currentTableModel = new DefaultTableModel(new Object [][] {},new String [] {"Title", "Release Year", "Rank"});
		ResultTable.setModel(currentTableModel);
		
		int requestID = executeBeforeLongRequest(new CommandToExecute() {
			
			@Override
			public void command(Object answer) {
				EControlMovies.this.numOfGenres = (Integer)answer;
				if(EControlMovies.this.numOfGenres > 0){
					int requestID = executeBeforeLongRequest(new CommandToExecute() {
						
						@SuppressWarnings("unchecked")
						@Override
						public void command(Object answer) {
							/*Update Genres select box*/
							currentDataGenresListModel = (List<Genre>) answer;
							currentGenresListModel = new DefaultListModel<String>();
							
							for(int i = 0; i < EControlMovies.this.currentDataGenresListModel.size(); i++){
								Genre genre = EControlMovies.this.currentDataGenresListModel.get(i);
								currentGenresListModel.insertElementAt(genre.getName(), i);
							}
							
							GenresList.setModel(currentGenresListModel);	
							
						}
					});
					
					kernel.getGenres(null, 0, EControlMovies.this.numOfGenres, requestID);
				}
			}
		});
		
		kernel.countGenres(null,null, requestID);
	}



	/*Search Panel*/
	/**
	 * Updates the search data only if data is valid
	 */
 	private boolean getSearchVariablesData(){
		/*Start by validating data*/
		
		int tmp_releaseYearMax = -1;
		int tmp_releaseYearMin = -1;
		float tmp_rankMax = -1;
		float tmp_rankMin = -1;
		
		
		if(!YearFromTextField.getText().equals("")){
			tmp_releaseYearMin = convertReleaseYear(YearFromTextField.getText());
			if(tmp_releaseYearMin == -1)
				return false;
		}
		
		if(!YearToTextField.getText().equals("")){
			tmp_releaseYearMax = convertReleaseYear(YearToTextField.getText());
			if(tmp_releaseYearMax == -1)
				return false;
		}
		
		if(!RankFromTextField.getText().equals("")){
			tmp_rankMin = convertRank(RankFromTextField.getText());
			if(tmp_rankMin == -1)
				return false;
		}
		
		if(!RankToTextField.getText().equals("")){
			tmp_rankMax = convertRank(RankToTextField.getText());
			if(tmp_rankMax == -1)
				return false;
		}
		
		
		releaseYearMin = tmp_releaseYearMin;
		releaseYearMax = tmp_releaseYearMax;
		rankMin = tmp_rankMin;
		rankMax = tmp_rankMax;
		
		if(!PartOfTitleTextField.getText().equals(""))
			titleSubStr = PartOfTitleTextField.getText();
		else
			titleSubStr = null;
		
		
		actor = selected_actor;
		director = selected_director;
		country = selected_country;
		
		/*Updated selected genres*/
		int[] selectedGenres = GenresList.getSelectedIndices();
		if(selectedGenres.length != 0){
			genres = new ArrayList<Genre>();
			for(int i = 0; i < selectedGenres.length; i++){
				genres.add(currentDataGenresListModel.get(selectedGenres[i]));
			}
		}else
			genres = null;
		
		return true;
	}

 	@Override
	protected void SearchButtonActionPerformed(ActionEvent evt) {
		if(unsavedChangesCheck(3)){
			if(getSearchVariablesData()){
				countResultAndPopulateTable(1);
			}
		}
	}
 	 	
 	protected void countResultAndPopulateTable(int page){
		
		final int pageWhenFinished = page;
		/*Command to execute after returning from*/
		int requestID = executeBeforeLongRequest(new CommandToExecute() {
			
			@Override
			public void command(Object answer) {
				/*Updated count & labels*/
				EControlMovies.this.count = Integer.parseInt(answer.toString());
				EControlMovies.this.FoundNumberLabel.setText(numbers_nf.format(EControlMovies.this.count));
				
				if(EControlMovies.this.count != 0)
					EControlMovies.this.currentPage = 1;
				else
					EControlMovies.this.currentPage = 0;
				
				EControlMovies.this.PageNumberLabel.setText(numbers_nf.format(EControlMovies.this.currentPage));
				EControlMovies.this.totalPages = (int) Math.ceil(((float)EControlMovies.this.count)/numberOfRecordsPerPage);
				EControlMovies.this.TotalPageNumberLabel.setText(numbers_nf.format(EControlMovies.this.totalPages));
									
				/*Get the data*/
				populateTableWithResults(pageWhenFinished);
				
			}
		});
	
		//TODO - delete this
		/*String actorName = "-NONE-";
		String directorName = "-NONE-";
		String countryName  = "-NONE-";
		String genresss = "-NONE-";
		
		if(actor != null)
			actorName = actor.toString();
		if(director != null)
			directorName = director.toString();
		if(country != null)
			countryName = country.toString();
		if(genres != null)
			genresss = Arrays.toString(genres.toArray());
			
		JOptionPane.showMessageDialog(this, String.format("TEST\nPartOfTitle: %s\nYear: %s-%s\nRank: %s-%s\nActor: %s\nDirector: %s\n" +
				"Country: %s\nGenres: %s", titleSubStr, releaseYearMin, releaseYearMax, 
				rankMin, rankMax, actorName, directorName, countryName, genresss));*/
		 
		kernel.countMovies(this.titleSubStr, this.releaseYearMin, this.releaseYearMax, this.rankMin, this.rankMax,
				this.actor, this.director, this.genres, this.country, requestID);
	}
	
	private void populateTableWithResults(int page){
		/*Command to execute after returning from*/
		
		final int pageNumberToSet = page;
		int requestID = executeBeforeLongRequest(new CommandToExecute() {
			
			@SuppressWarnings("unchecked")
			@Override
			public void command(Object answer) {
				if(answer != null){
					EControlMovies.this.currentDataInTableModel = (List<Movie>) answer;
					
					/*Create new table model, and insert the rows*/
					currentTableModel = new DefaultTableModel(new Object [][] {},new String [] {"Title", "Release Year", "Rank"});
					currentTableModel.addTableModelListener(new TableModelListener() {
						
						@Override
						public void tableChanged(TableModelEvent e) {
							tableChangedEventHandler(e);
						}
					});
					
					for(int i = 0; i < EControlMovies.this.currentDataInTableModel.size(); i++){
						Movie movie = EControlMovies.this.currentDataInTableModel.get(i);
						Object[] rowData = new Object[] {movie.getTitle(), movie.getReleaseYear(), movie.getRank()};
						currentTableModel.insertRow(i, rowData);
					}
					
					
					ResultTable.setModel(currentTableModel);
					if(EControlMovies.this.count != 0)
						currentPage = pageNumberToSet;
					else
						currentPage = 0;
					
					updateButtonsAndLabelsAfterReturnedResultSet();
				}
			}
		});
		
		int from = (page <= 0) ? 0 : (page-1)*numberOfRecordsPerPage;
		int to = (page <= 0) ? 0 : page*numberOfRecordsPerPage;
		
		kernel.getMovies(titleSubStr, releaseYearMin, releaseYearMax, rankMin, rankMax,
					actor, director, genres, country, from, to, requestID);
	}
 	
	@Override
	protected void ActorButtonActionPerformed(ActionEvent evt) {
		
		openAnotherFrame(EControlActors.class, false, new CommandToExecute() {
			
			@Override
			public void command(Object answer) {
				EControlMovies.this.selected_actor = (Actor)answer;
				if(EControlMovies.this.selected_actor != null){
					EControlMovies.this.ActorNameTextField.setText(EControlMovies.this.selected_actor.getLastName() + 
							", " + EControlMovies.this.selected_actor.getFirstName());
				}else{
					EControlMovies.this.ActorNameTextField.setText("");
				}
				
			}
		});

	}

	@Override
	protected void CountryButtonActionPerformed(ActionEvent evt) {
	openAnotherFrame(EControlCountries.class, false, new CommandToExecute() {
			
			@Override
			public void command(Object answer) {
				EControlMovies.this.selected_country = (Country)answer;
				if(EControlMovies.this.selected_country != null){
					EControlMovies.this.CountryNameTextField.setText(EControlMovies.this.selected_country.getName());
				}else{
					EControlMovies.this.CountryNameTextField.setText("");
				}
				
			}
		});


	}

	@Override
	protected void DirectorButtonActionPerformed(ActionEvent evt) {
		openAnotherFrame(EControlDirectors.class, false, new CommandToExecute() {
			
			@Override
			public void command(Object answer) {
				EControlMovies.this.selected_director = (Director)answer;
				if(EControlMovies.this.selected_director != null){
					EControlMovies.this.DirectorNameTextField.setText(EControlMovies.this.selected_director.getLastName() + 
							", " + EControlMovies.this.selected_director.getFirstName());
				}else{
					EControlMovies.this.DirectorNameTextField.setText("");
				}
				
			}
		});
	}

	@Override
	protected void ClearButtonActionPerformed(ActionEvent evt) {
		PartOfTitleTextField.setText("");
		YearFromTextField.setText("");
		YearToTextField.setText("");
		RankFromTextField.setText("");
		RankToTextField.setText("");
		ActorNameTextField.setText("");
		DirectorNameTextField.setText("");
		CountryNameTextField.setText("");
		selected_actor = null;
		selected_country = null;
		selected_director = null;
		GenresList.setSelectedIndices(new int[0]);
	}
	
	/*Table Panel*/
	

	@Override
	protected void NumOfRecordsInPageComboBoxActionPerformed(ActionEvent evt) {
		if(unsavedChangesCheck(3)){
			numberOfRecordsPerPage = Integer.parseInt(NumOfRecordsInPageComboBox.getSelectedItem().toString());
			
			/*fix problem when the user is on page 100 in 5rec-per-page but there is no page 100 in 100rec-per-page*/
			int expectedTotalPages = (int) Math.ceil(((float)EControlMovies.this.count)/numberOfRecordsPerPage);
	
			
			if(currentPage > expectedTotalPages)
				currentPage = expectedTotalPages;
			
			populateTableWithResults(currentPage);
		}
	}
	
	@Override
	protected void PreviousButtonActionPerformed(ActionEvent evt) {
		if(unsavedChangesCheck(3)){
			if(currentPage > 1){
				int askingPage = currentPage-1;
				populateTableWithResults(askingPage);
			}else{
				populateTableWithResults(totalPages);
			}
		}
	}

	@Override
	protected void NextButtonActionPerformed(ActionEvent evt) {
		if(unsavedChangesCheck(3)){
			if(currentPage < totalPages){
				int askingPage = currentPage+1;
				populateTableWithResults(askingPage);
			}else{
				populateTableWithResults(1);
			}
		}
	}
	
	
	private void updateButtonsAndLabelsAfterReturnedResultSet(){
		EControlMovies.this.PageNumberLabel.setText(String.valueOf(EControlMovies.this.currentPage));
		EControlMovies.this.totalPages = (int) Math.ceil(((float)EControlMovies.this.count)/numberOfRecordsPerPage);
		EControlMovies.this.TotalPageNumberLabel.setText(String.valueOf(EControlMovies.this.totalPages));
		
		if(totalPages == 0){
			NextButton.setEnabled(false);
			PreviousButton.setEnabled(false);
			NumOfRecordsInPageComboBox.setEnabled(false);
		}else{
			NextButton.setEnabled(true);
			PreviousButton.setEnabled(true);
			NumOfRecordsInPageComboBox.setEnabled(true);
		}
					
	}

	protected void tableChangedEventHandler(TableModelEvent e){
		if(!isCalledAsLongRequestFromOtherFrame()){
			if(e.getType() == TableModelEvent.UPDATE){/*If this is update*/
				int rownum = e.getFirstRow();
				if(rownum != currentNewRow){
					/*if the row we are changing isn't the currentNewRow*/
					if(currentNewRow != -1){
						/*if we started insert - don't allow it*/
						int userAnswer = JOptionPane.showConfirmDialog(this, "You cannot update while in insert.\n" +
								"Do you wish to commit your previous change?\n" +
								"(pressing no will discard your change)", "", JOptionPane.YES_NO_OPTION);
						switch(userAnswer){
							case JOptionPane.YES_OPTION:
								/*discard current change*/
								undoChangesToRow(rownum);
								/*Updating previous changes*/
								insertNewRecordIntoDB();
								break;
							case JOptionPane.NO_OPTION:
								/*Discarding previous changes*/
								currentTableModel.removeRow(EControlMovies.this.currentNewRow);
								InsertButton.setForeground(DeleteButton.getForeground());
								UpdateButton.setForeground(Color.red);
								currentNewRow = -1;
								currentRowBeingUpdated = rownum;
						}
					}else{/*we havent started insert*/
						if(currentRowBeingUpdated == -1){
							currentRowBeingUpdated = rownum;
							UpdateButton.setForeground(Color.red);
						}else if(currentRowBeingUpdated != rownum){
							int userAnswer = JOptionPane.showConfirmDialog(this, "You can only update one row at a time.\n" +
									"Do you wish to commit your previous change?\n" +
									"(pressing no will discard your change)", "", JOptionPane.YES_NO_OPTION);
							switch(userAnswer){
								case JOptionPane.YES_OPTION:
									/*discard current change*/
									undoChangesToRow(rownum);
									/*Updating previous changes*/
									updateChangesInTable();
									break;
								case JOptionPane.NO_OPTION:
									/*Discarding previous changes*/
									undoChangesToRow(currentRowBeingUpdated);
									UpdateButton.setForeground(Color.red);
									currentRowBeingUpdated = rownum;
							}
						}
					}
				
				}	
			}
		}
	}
	
	private void undoChangesToRow(int rowNum){
		currentTableModel.removeRow(rowNum);
		Movie movie = currentDataInTableModel.get(rowNum);
		currentTableModel.insertRow(rowNum, new Object[] {movie.getTitle(), movie.getReleaseYear(), movie.getRank()	});
	}
	
	/**
	 * 
	 * @return true if there aren't any unsaved changed, otherwise false
	 */
	private boolean unsavedChangesCheck(int create_update_all){
		if(currentRowBeingUpdated != -1 && create_update_all != 2){
			int userAnswer = JOptionPane.showConfirmDialog(this, "You have unsaved change.\n" +
					"Do you wish to update the record?\n" +
					"(pressing no will discard your change)", "", JOptionPane.YES_NO_OPTION);
			switch(userAnswer){
				case JOptionPane.YES_OPTION:
					/*Updating change*/
					updateChangesInTable();
					return false;
				case JOptionPane.NO_OPTION:
					/*Discarding change*/
					undoChangesToRow(currentRowBeingUpdated);
					UpdateButton.setForeground(DeleteButton.getForeground());
					currentRowBeingUpdated = -1;
					return true;
			}
		}else if(currentNewRow != -1 && create_update_all != 1){
			int userAnswer = JOptionPane.showConfirmDialog(this, "You have unsaved change.\n" +
					"Do you wish to insert the record?\n" +
					"(pressing no will discard your record)", "", JOptionPane.YES_NO_OPTION);
			switch(userAnswer){
				case JOptionPane.YES_OPTION:
					/*Updating change*/
					insertNewRecordIntoDB();
					return false;
				case JOptionPane.NO_OPTION:
					/*Discarding change*/
					currentTableModel.removeRow(EControlMovies.this.currentNewRow);
					InsertButton.setForeground(DeleteButton.getForeground());
					currentNewRow = -1;
					return true;
		}
		}
		
		return true;
	}
 	
	/*Action Panel*/
	

	

	@Override
	protected void DeleteButtonActionPerformed(ActionEvent evt) {
		if(unsavedChangesCheck(3)){
			int[] selectedRowIndexes = ResultTable.getSelectedRows();
			if(selectedRowIndexes.length != 1){
				JOptionPane.showMessageDialog(this, "Please select ONE record to delete");
			}else{
				/*Command to execute after returning from*/
				int requestID = executeBeforeLongRequest(new CommandToExecute() {
					
					@Override
					public void command(Object answer) {
						//TODO - check if this is always right
						if(currentDataInTableModel.size() != 1)
							EControlMovies.this.countResultAndPopulateTable(currentPage);
						else
							EControlMovies.this.countResultAndPopulateTable(--currentPage);
					}
				});
				
				Movie movie = this.currentDataInTableModel.get(ResultTable.convertRowIndexToModel(selectedRowIndexes[0]));
				kernel.actionMovie(ACTION.DELETE, movie, requestID);
			}
		}
	}

	@Override
	protected void UpdateButtonActionPerformed(ActionEvent evt) {
		if(currentRowBeingUpdated == -1){
			JOptionPane.showMessageDialog(this, "There are no changes to commit.");
		}else{
			updateChangesInTable();
		}

	}
	
	private Movie parseDataFromTable(Movie movieToUpdate, int rowNum){
		//TODO - this change selection doesn't help so much..(for some reason the selected jumps..)
		ResultTable.changeSelection(rowNum, 1, false, false);
		
		String newMovieTitle = currentTableModel.getValueAt(rowNum, 0).toString();
		String str_newMovieReleaseYear = currentTableModel.getValueAt(rowNum, 1).toString();
		String str_newMovieRank = currentTableModel.getValueAt(rowNum, 2).toString();
		
		int newMovieReleaseYear = convertReleaseYear(str_newMovieReleaseYear);
		if(newMovieReleaseYear == -1)
			return null;
		
		float newMovieRank = convertRank(str_newMovieRank);
		if(newMovieRank == -1.0F)
			return null;
		
		return new Movie(movieToUpdate.getId(), newMovieTitle, newMovieReleaseYear, newMovieRank);
	}
	
	private void updateChangesInTable(){
		if(unsavedChangesCheck(2)){/*pass update mode*/
			/*Parse changes*/
			//TODO - this change selection doesn't help so much..(for some reason the selected jumps..)
			ResultTable.changeSelection(currentRowBeingUpdated, 1, false, false);
			
			
			final Movie updatedMovie = parseDataFromTable(currentDataInTableModel.get(currentRowBeingUpdated),
					currentRowBeingUpdated);
			if(updatedMovie != null){/*If the parsing succeeded*/
				/*Command to execute after returning from*/
				int requestID = executeBeforeLongRequest(new CommandToExecute() {
					
					@Override
					public void command(Object answer) {
						EControlMovies.this.currentDataInTableModel.remove(EControlMovies.this.currentRowBeingUpdated);
						EControlMovies.this.currentDataInTableModel.add(EControlMovies.this.currentRowBeingUpdated, updatedMovie);
						UpdateButton.setForeground(DeleteButton.getForeground());
						EControlMovies.this.currentRowBeingUpdated = -1;
					}
				});
				
				
				kernel.actionMovie(ACTION.UPDATE, updatedMovie, requestID);
			}
		}
	}
	
	private int convertReleaseYear(String str_releaseYear){
		int tmp_releaseYear = -1;
		try{
			tmp_releaseYear = Integer.parseInt(str_releaseYear);
		}catch(NumberFormatException e){
			JOptionPane.showMessageDialog(this, "A year must consist only of numbers and be in this format: YYYY");
		}
		
		return tmp_releaseYear;
	}
	
	private float convertRank(String str_rank){
		float tmp_rank = -1.0F;
		
		try{
			tmp_rank = Float.parseFloat(str_rank);
		}catch(NumberFormatException e){
			JOptionPane.showMessageDialog(this, "A rank is consisted solely of numbers (and an optional point)");
		}
		
		return tmp_rank;
	}

	@Override
	protected void InsertButtonActionPerformed(ActionEvent evt) {
		if(currentRowBeingUpdated != -1){
			JOptionPane.showMessageDialog(this, "Please finish the update before inserting a new row.");
			return;
		}
		if(unsavedChangesCheck(1)){/*pass insert mode*/
			if(currentNewRow == -1){
				InsertButton.setForeground(Color.red);
				currentTableModel.addRow(new Object[]{"", "", ""});
				currentNewRow = currentTableModel.getRowCount()-1;
				ResultTable.changeSelection(currentNewRow, 1, false, false);
			}else{
				insertNewRecordIntoDB();
			}
		}

	}
	
	private void insertNewRecordIntoDB(){
		final Movie newMovie = parseDataFromTable(new Movie(),
				currentNewRow);
		
		if(newMovie != null){/*If the parsing succeeded*/
			/*Command to execute after returning from*/
			int requestID = executeBeforeLongRequest(new CommandToExecute() {
				
				@Override
				public void command(Object answer) {
					currentTableModel.removeRow(EControlMovies.this.currentNewRow);
					EControlMovies.this.currentNewRow = -1;
					InsertButton.setForeground(DeleteButton.getForeground());
					if(EControlMovies.this.currentPage != 0){/*If we are not inserting new records into empty set*/
						countResultAndPopulateTable(EControlMovies.this.currentPage);
					}
					
				}
			});
			
			
			kernel.actionMovie(ACTION.CREATE, newMovie, requestID);
		}
	}

 	
	/*Connections Panel*/
	


	@Override
	protected void ShowMovieActorsConButtonActionPerformed(ActionEvent evt) {
		if(unsavedChangesCheck(3)){
			int[] selectedRowIndexes = ResultTable.getSelectedRows();
			if(selectedRowIndexes.length != 1){
				JOptionPane.showMessageDialog(this, "Please select ONE record in order to see it's connections");
			}else{
				Movie movie = this.currentDataInTableModel.get(ResultTable.convertRowIndexToModel(selectedRowIndexes[0]));
				openPreCreatedFrame(new EConnectionsFrame(EConnectionsFrame.CONNECTION_TYPE.Movie,
						movie, EConnectionsFrame.CONNECTION_TYPE.Actor), null);
			}
		}
	}

	@Override
	protected void ShowMovieDirectorsConButtonActionPerformed(ActionEvent evt) {
		if(unsavedChangesCheck(3)){
			int[] selectedRowIndexes = ResultTable.getSelectedRows();
			if(selectedRowIndexes.length != 1){
				JOptionPane.showMessageDialog(this, "Please select ONE record in order to see it's connections");
			}else{
				Movie movie = this.currentDataInTableModel.get(ResultTable.convertRowIndexToModel(selectedRowIndexes[0]));
				openPreCreatedFrame(new EConnectionsFrame(EConnectionsFrame.CONNECTION_TYPE.Movie,
						movie, EConnectionsFrame.CONNECTION_TYPE.Director), null);
			}
		}

	}

	@Override
	protected void ShowMovieGenresConButtonActionPerformed(ActionEvent evt) {
		if(unsavedChangesCheck(3)){
			int[] selectedRowIndexes = ResultTable.getSelectedRows();
			if(selectedRowIndexes.length != 1){
				JOptionPane.showMessageDialog(this, "Please select ONE record in order to see it's connections");
			}else{
				Movie movie = this.currentDataInTableModel.get(ResultTable.convertRowIndexToModel(selectedRowIndexes[0]));
				openPreCreatedFrame(new EConnectionsFrame(EConnectionsFrame.CONNECTION_TYPE.Movie,
						movie, EConnectionsFrame.CONNECTION_TYPE.Genre), null);
			}
		}

	}

	@Override
	protected void ShowMovieCountriesConButtonActionPerformed(ActionEvent evt) {
		if(unsavedChangesCheck(3)){
			int[] selectedRowIndexes = ResultTable.getSelectedRows();
			if(selectedRowIndexes.length != 1){
				JOptionPane.showMessageDialog(this, "Please select ONE record in order to see it's connections");
			}else{
				Movie movie = this.currentDataInTableModel.get(ResultTable.convertRowIndexToModel(selectedRowIndexes[0]));
				openPreCreatedFrame(new EConnectionsFrame(EConnectionsFrame.CONNECTION_TYPE.Movie,
						movie, EConnectionsFrame.CONNECTION_TYPE.Country), null);
			}
		}
	}

 	
	/*Going back*/
	
	@Override
	protected void BackButtonActionPerformed(ActionEvent evt) {
		if(unsavedChangesCheck(3)){
			if(isCalledAsLongRequestFromOtherFrame()){
				int selectedRowIndx = ResultTable.getSelectedRow();
				if(selectedRowIndx != -1 && currentDataInTableModel != null){
					Movie movieAnswer = currentDataInTableModel.get(ResultTable.convertRowIndexToModel(selectedRowIndx));
					setAnswerToCallingFrame(movieAnswer);
				}
				returnToCallingFrame();
			}else{
				openAnotherFrame(EControlPanelMenuFrame.class, true);
			}
		}
	}


	@Override
	protected void setWindowComponentsWhenCalledFromAnotherFrame() {
		if(isCalledAsLongRequestFromOtherFrame()){
			DeleteButton.setEnabled(false);
			UpdateButton.setEnabled(false);
			InsertButton.setEnabled(false);
			ShowMovieActorsConButton.setEnabled(false);
			ShowMovieDirectorsConButton.setEnabled(false);
			ShowMovieGenresConButton.setEnabled(false);
			ShowMovieCountriesConButton.setEnabled(false);
			ActorButton.setEnabled(false);
			DirectorButton.setEnabled(false);
			CountryButton.setEnabled(false);
			BackButton.setText("SELECT");
		}
		
	}




}
